package qldc.pm.ksdl.action;

import java.io.File;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletPreferences;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import qldc.pm.csdl.cd90.model.jaxb.CongDanJAXB;
import qldc.pm.csdl.cd90.model.jaxb.RootJAXB;
import qldc.pm.csdl.cd90.util.CongDanJAXBUtil;
import qldc.pm.ksdl.util.KSDLConstants;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;

public class ImportDanCuAction {
	
	private static final Log LOG = LogFactoryUtil.getLog(DanhSachDanCuAction.class);
	
	public static void submitUploadForm(ActionRequest actionRequest, ActionResponse actionResponse){
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
		boolean signedIn = themeDisplay.isSignedIn();
		
		if(signedIn){
			try {
				UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
				String xmlFilePathKey = KSDLConstants.XML_FILE_NAME + themeDisplay.getUserId();
				
				File congDanXML = uploadRequest.getFile(KSDLConstants.XML_FILE_NAME);
				// Get upload file bytes
				byte[] congDanXMLBytes = FileUtil.getBytes(congDanXML);
				
				if(null != congDanXMLBytes){
					JAXBContext jaxbContext = JAXBContext.newInstance(RootJAXB.class);
					Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
					RootJAXB root = (RootJAXB) jaxbUnmarshaller.unmarshal(congDanXML);
					
					if(null != root){
						List<CongDanJAXB> congDanList = root.getCongDanList();
						actionRequest.getPortletSession().setAttribute(KSDLConstants.CONG_DAN_LIST, congDanList);
					}
					
//					Document d = SAXReaderUtil.read(congDanXML);
//					
//					Node node = d .selectSingleNode("/danhSachCongDan/congDan[@name='"  + title + "']/dynamic-content");
					
					PortletPreferences portletPreferences = actionRequest.getPreferences();
					
					String storedXmlFilePath = portletPreferences.getValue(xmlFilePathKey, StringPool.BLANK);
					String newXmlFilePath = congDanXML.getAbsolutePath();
					
					if(storedXmlFilePath.equals(StringPool.BLANK) || !storedXmlFilePath.equals(newXmlFilePath)){
						FileUtil.delete(storedXmlFilePath);
						
						portletPreferences.setValue(xmlFilePathKey, congDanXML.getAbsolutePath());
						portletPreferences.store();
					}
					
					// Add success message if there is no error occurs
					SessionMessages.add(actionRequest.getPortletSession(), "yeu-cau-cua-ban-duoc-thuc-hien-thanh-cong");
				} else {
					SessionErrors.add(actionRequest, "vui-long-chon-file-de-upload");
				}
				
				goToImportPage(actionResponse);
			} catch (Exception e) {
				SessionErrors.add(actionRequest, "gap-loi-xu-ly-vui-long-xem-server-log");
				LOG.error(e);
				goToImportPage(actionResponse);
			}
		}
		
		// Hide default error message
		SessionMessages.add(actionRequest, PortalUtil.getPortletId(actionRequest) + SessionMessages. KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
	}
	
	public static void submitContentForm(ActionRequest actionRequest, ActionResponse actionResponse){
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
		boolean signedIn = themeDisplay.isSignedIn();
		
		if(signedIn){
			try {
				String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
				
				if(cmd.equals(KSDLConstants.IMPORT_TAT_CA_VAO_DB)){
					List<CongDanJAXB> cdJAXBList = (List<CongDanJAXB>) actionRequest.getPortletSession().getAttribute(KSDLConstants.CONG_DAN_LIST);
					
					CongDanJAXBUtil.importCongDanJAXBToDB(cdJAXBList);
				}
				
			} catch (Exception e) {
				SessionErrors.add(actionRequest, "gap-loi-xu-ly-vui-long-xem-server-log");
				LOG.error(e);
				goToImportPage(actionResponse);
			}
		}
		
		// Hide default error message
		SessionMessages.add(actionRequest, PortalUtil.getPortletId(actionRequest) + SessionMessages. KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
	}
	
	private static void goToImportPage(ActionResponse actionResponse){
		actionResponse.setRenderParameter("mainTabs", KSDLConstants.IMPORT_DAN_CU_90);
		actionResponse.setRenderParameter("idcTabs", KSDLConstants.UPLOAD);
	}
}
